import { constantRouterMap } from '@/router'
import { asyncRouterData, constantRouterData } from '@/router/menu'
import {getStorage} from "@/utils/auth";
import * as stn from "@/constants/storeName";


let menuList = []
console.log(menuList, 'menuList')
/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */
function hasPermission (roles, route) {
  //console.log(roles, route, 'roles, route')
  let currMenu = menuList.find(item=>item.name===route.name)
  ////debugger
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } if (currMenu && currMenu.sortby) {
    route.sortby = currMenu.sortby
    return true
  } else {
    return true
  }
}
// function getMenu (name) {
//   for (let i = 0; i < menuList.length; i++) {
//     let menu = menuList[i]
//     if (name === menu.name) {
//       return menu
//     }
//   }
//   return null
// }

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param routes asyncRouterMap
 * @param roles
 */
function filterAsyncRouter (routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRouter(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  return res
}
// 对菜单进行排序
function sortRouters (accessedRouters) {
  for (let i = 0; i < accessedRouters.length; i++) {
    let router = accessedRouters[i];
    if (router.children && router.children.length > 0){
      router.children.sort(compare("sortby"));
    }
  }
  accessedRouters.sort(compare("sortby"));
}

// 降序比较函数
function compare (p) {
  return function (m, n) {
    let a = m[p]
    let b = n[p]
    return a - b
  }
}

const permission = {
  state: {
    routers: constantRouterMap, // 公共菜单
    addRouters: [] // 动态菜单
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterData().concat(routers) // constantRouterMap.concat(routers)
    }
  },
  actions: {
    GenerateRoutes ({ commit }, data) {
      return new Promise(resolve => {
        //debugger
        const { roles } = data
        let accessedRouters = null
        menuList = getStorage(stn.MENU_LIST) ? getStorage(stn.MENU_LIST) : ''
        if (roles.includes('admin')) {
          accessedRouters = asyncRouterData()
        } else {
          accessedRouters = filterAsyncRouter(asyncRouterData(), roles)
        }
        // 路由排序
        sortRouters(accessedRouters)
        //console.log(accessedRouters, 'accessedRouters')
        commit('SET_ROUTERS', accessedRouters)
        // sessionStorage.setItem("routers12",JSON.stringify(accessedRouters))
        // sessionStorage.setItem("routers12333",JSON.stringify(constantRouterData().concat(accessedRouters)))
        resolve()
      })
    }
  }
}

export default permission
